package org.yunai.swjg.server.core.spring;

import org.apache.mina.core.filterchain.IoFilterChainBuilder;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.yunai.swjg.server.core.GameServer;

/**
 * Server工厂Bean
 * User: yunai
 * Date: 13-3-16
 * Time: 下午5:09
 */
public class ServerFactoryBean implements FactoryBean<GameServer>, InitializingBean {

    private GameServer server;

    private NioSocketAcceptor acceptor;

    private IoSessionConfig sessionConfig;

    private IoHandler handler;

    private IoFilterChainBuilder filters;

    private Integer port;

    @Override
    public GameServer getObject() throws Exception {
        return server;
    }

    @Override
    public Class<?> getObjectType() {
        return GameServer.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // CHECK
        if (acceptor == null) {
            throw new NullPointerException("[acceptor]不允许空!");
        }
        if (handler == null) {
            throw new Error("[handler]不允许空!");
        }
        if (port == null) {
            throw new Error("[port]不允许空!");
        }
        acceptor.setHandler(handler);
        acceptor.setFilterChainBuilder(filters);
        server = new GameServer();
        server.setAcceptor(acceptor);
        if (sessionConfig != null) {
            acceptor.getSessionConfig().setAll(sessionConfig);
        }

        server.setPort(port);
        // 清空下属性值
        clearPropertiesSet();

        // 启动
        server.start();
    }

    private void clearPropertiesSet() {
        this.acceptor = null;
        this.sessionConfig = null;
        this.handler = null;
        this.filters = null;
        this.port = null;
    }

    public void setAcceptor(NioSocketAcceptor acceptor) {
        this.acceptor = acceptor;
    }

    public void setFilters(IoFilterChainBuilder filters) {
        this.filters = filters;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setHandler(IoHandler handler) {
        this.handler = handler;
    }

    public void setSessionConfig(IoSessionConfig sessionConfig) {
        this.sessionConfig = sessionConfig;
    }
}
